package com.springmvcstartup.web;

import com.springmvcstartup.domain.Person;
import com.springmvcstartup.service.PersonService;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;

import javax.annotation.Resource;
import java.util.List;

/**
 * Main entry point for all person related REST calls.
 *
 * @author Ceren Akkan
 */
@Controller
public class PersonController {

    @Resource(name = "personService")
    private PersonService personService;

    @RequestMapping(value = "/person", method = RequestMethod.POST)
    @ResponseStatus(HttpStatus.CREATED)
    @ResponseBody
    public ModelAndView create(@RequestBody Person person) {
        Person result = personService.create(person);
        ModelAndView model = new ModelAndView("person");
        model.addObject("person", result);
        return model;
    }

    @RequestMapping(value = "/person", method = RequestMethod.PUT)
    @ResponseBody
    public void update(@RequestBody Person person) {
        personService.update(person);
    }

    @RequestMapping(value = "/person/{personId}", method = RequestMethod.GET)
    public ModelAndView get(@PathVariable Long personId) {
        final Person person = personService.get(personId);
        ModelAndView model = new ModelAndView("person");
        model.addObject("person", person);
        return model;
    }

    @RequestMapping(value = "/person", method = RequestMethod.GET)
    public ModelAndView get() {
        final List<Person> result = personService.get();
        ModelAndView model = new ModelAndView("personList");
        model.addObject("personList", result);
        return model;
    }

    @RequestMapping(value = "/person/{personId}", method = RequestMethod.DELETE)
    public void delete(@PathVariable Long personId) {
        personService.delete(personId);
    }

    /**
     * Sets the person service
     *
     * @param personService
     */
    public void setPersonService(PersonService personService) {
        this.personService = personService;
    }

}
